<?php


class ConfigService extends TP_Service
{
	private $role;

	public function __construct()
	{
		parent::__construct();
		$this->load->model("SModel/Config_model");
		$this->role = $this->getRole($_SESSION[SESS_UUID]);
	}

	// 能否操作
	private function hasPre() {
		if ($this->role->role_id != WebRole::Manage[TPEnum::Value]) {
			exit(retJson(ErrCode::ErrCode_10404));
		}
	}

	public function getConfigList() {
		return $this->Config_model->get_list_full();
	}

	public function delConfig($param) {
		if (!isset($param['id'])) {
			exit(retJson(ErrCode::ErrCode_10002));
		}

		$this->Config_model->delete(['id' => $param['id']]);
		return true;
	}

	public function saveConfig($param) {
		if (!isset(
			$param['key'],
			$param['name'],
			$param['value'],
		)) {
			exit(retJson(ErrCode::ErrCode_10002));
		}

		$this->hasPre();

		$data = [
			'key' => $param['key'],
			'name' => $param['name'],
			'value' => $param['value'],
			'is_arr' => 0
		];

		if (isset($param['is_arr'])) {
			$data['is_arr'] = $param['is_arr'];
		}

		if (empty($param['id'])) {
			$this->Config_model->add($data);
		} else {
			$this->Config_model->update($data, ['id' => $param['id']]);
		}

		return true;
	}

	public function getConfigJson() {
		$data = $this->Config_model->get_list_full();
		$output = [];

		foreach ($data as &$item) {
			if ($item['is_arr'] == 1) {
				$item['value'] = explode('|', $item['value']);
			}

			$output[$item['key']] = $item['value'];
		}

		return $output;
	}

}
